import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as crypto from 'crypto';

@Injectable()
export class KeyGeneratorService {
  constructor(private configService: ConfigService) {}

  generateRandomKey(length: number): string {
    return crypto.randomBytes(length).toString('hex');
  }

  async addSecretKeyToEnv() {
    const keyLength = 128; // 生成密钥的字节长度
    const randomKey = this.generateRandomKey(keyLength);
    const envFilePath = '.env';
    
    // 读取现有的 .env 文件
    let envContent = '';

    // 检查 .env 文件是否存在
    if (fs.existsSync(envFilePath)) {
      envContent = fs.readFileSync(envFilePath, 'utf8');
    }

    // 检查是否已经存在 SECRET_KEY 变量
    if (envContent.includes('SECRET_KEY=')) {
      console.log('SECRET_KEY already exists in .env file.');
    } else {
      // 将新生成的密钥写入 .env 文件
      fs.appendFileSync(envFilePath, `\nSECRET_KEY=${randomKey}\n`);
      console.log(`Generated new SECRET_KEY and added to .env: ${randomKey}`);
    }
  }
}
